package com.example.web.controller;

import com.example.web.mapper.CartMapper;
import com.example.web.mapper.ProductMapper;
import com.example.web.model.Product;
import com.example.web.model.ShoppingCart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Create by keboom on 2020/7/7
 */
@Controller
public class CartController {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;

    /**
     * 获取用户购物车信息
     * @param session
     * @param model
     * @return
     */
    @GetMapping("/mall/cart")
    public String cart(HttpSession session, Model model){
        List<ShoppingCart> carts = cartMapper.selectCart((String) session.getAttribute("username"));
        List<Product> products = new ArrayList<>();
        Integer sum = 0;
        for (ShoppingCart cart : carts) {
            Integer productId = cart.getProductId();
            Product product = productMapper.selectById(productId);
            sum += product.getProductPrice();
            products.add(product);
        }
        model.addAttribute("products",products);
        model.addAttribute("sum",sum);
        System.out.println("hahaha");
        return "cart";
    }

    /**
     * 结算购物车，直接将购物车清空了。。
     * @param session
     * @return
     */
    @GetMapping("/mall/cart/done")
    public String cartDone(HttpSession session){
        cartMapper.deleteByUsername((String) session.getAttribute("username"));
        return "redirect:/mall/cart";
    }
}
